let NfcAdapter;
let nfc;
let nfcCallback;
let NdefRecord;
let NdefMessage;
let nfcType = 'cardNo'
let nfcwriteText = ''

export function initNFC(callback) {
	if (uni.getSystemInfoSync().platform == 'android') {
		nfcCallback = callback;
		init();
	}
}

export function closeNFC() {
	nfcCallback = null;
	if (uni.getSystemInfoSync().platform == 'android') {
		close();
	}
}

export function setNfcType(e) {
	if (!['cardNo', 'write', 'read'].includes(e)) {
		showToast('类型不正确')
		return
	}
	nfcType = e
}

export function setNfcText(e) {
	nfcwriteText = e
}

function init() {
	try {
		let main = plus.android.runtimeMainActivity();
		let Intent = plus.android.importClass('android.content.Intent');
		let Activity = plus.android.importClass('android.app.Activity');
		let PendingIntent = plus.android.importClass('android.app.PendingIntent');
		let IntentFilter = plus.android.importClass('android.content.IntentFilter');
		NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
		nfc = NfcAdapter.getDefaultAdapter(main);

		if (nfc == null) {
			uni.showToast({
				title: '设备不支持NFC！',
				icon: 'none'
			})
			return;
		}

		if (!nfc.isEnabled()) {
			uni.showToast({
				title: '请在系统设置中先启用NFC功能！',
				icon: 'none'
			});
			return;
		}

		let intent = new Intent(main, main.getClass());
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		let pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
		let ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
		let tag = new IntentFilter('android.nfc.action.TAG_DISCOVERED');
		ndef.addDataType("*/*");
		let intentFiltersArray = [ndef, tag];
		let techListsArray = [
			["android.nfc.tech.MifareClassic"],
			["android.nfc.tech.MifareUltralight"]
		];
		plus.globalEvent.addEventListener("newintent",
			function() {
				readCardNo();
			}, false);
		plus.globalEvent.addEventListener("pause", function(e) {
			if (nfc) {
				nfc.disableForegroundDispatch(main);
			}
		}, false);
		plus.globalEvent.addEventListener("resume", function(e) {
			if (nfc) {
				nfc.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
			}
		}, false);
		nfc.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
	} catch (e) {
		console.error(e);
	}
}

/**
 * 监听
 */
function readCardNo() {
	NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
	NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
	var main = plus.android.runtimeMainActivity();
	var intent = main.getIntent();
	console.log("action type:" + intent.getAction());
	if ("android.nfc.action.TECH_DISCOVERED" == intent.getAction()) {
		if (nfcType === 'cardNo') {
			__read_no(intent)
		} else if (nfcType === 'write') {
			__write(intent);
		} else {
			__read(intent);
		}
		// __write(intent);
		// __read(intent);
	}
	// let m1;
	// try {
	// 	let main = plus.android.runtimeMainActivity();
	// 	let intent = main.getIntent();
	// 	console.log("intent.getAction()", intent.getAction());
	// 	if ("android.nfc.action.TECH_DISCOVERED" == intent.getAction()) {
	// 		let tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	// 		let MifareClassic = plus.android.importClass("android.nfc.tech.MifareClassic");
	// 		m1 = MifareClassic.get(tag);
	// 		m1.connect();
	// 		if (m1.isConnected()) {
	// 			let sector = 1;
	// 			let result = m1.authenticateSectorWithKeyA(sector, hexStringToByteArray("B193C384D576"));
	// 			if (result) {
	// 				let blockIndex = m1.sectorToBlock(sector);
	// 				let data = m1.readBlock(blockIndex);
	// 				let cardNo = byteArrayToHexString(data);
	// 				if (nfcCallback) {
	// 					nfcCallback(cardNo);
	// 				}
	// 			} else {
	// 				uni.showToast({
	// 					title: "密钥认证错误",
	// 					icon: 'none'
	// 				});
	// 			}
	// 		} else {
	// 			uni.showToast({
	// 				title: "寻卡失败",
	// 				icon: 'none'
	// 			});
	// 		}
	// 	}
	// } catch (e) {
	// 	uni.showToast({
	// 		title: "读卡失败",
	// 		icon: 'none'
	// 	});
	// } finally {
	// 	if (m1 != null) {
	// 		try {
	// 			m1.close();
	// 		} catch (e) {
	// 			console.log("关闭标签失败");
	// 		}
	// 	}
	// }
}

function showToast(msg) {
	uni.showToast({
		title: msg,
		icon: 'none'
	})
}
/**
 * 写入内容
 */
function __write(intent) {
	if (!nfcwriteText) {
		showToast('写入内容不能为空')
		return
	}
	var text = nfcwriteText
	var textBytes = plus.android.invoke(text, "getBytes");
	var textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
		plus.android.invoke("text/plain", "getBytes"), plus.android.invoke("", "getBytes"), textBytes);
	var message = new NdefMessage([textRecord]);
	var Ndef = plus.android.importClass('android.nfc.tech.Ndef');
	var NdefFormatable = plus.android.importClass('android.nfc.tech.NdefFormatable');
	var tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	var ndef = Ndef.get(tag);
	if (ndef != null) {
		var size = message.toByteArray().length;
		console.log("size=" + size);
		ndef.connect();
		if (!ndef.isWritable()) {
			showToast("tag不允许写入");
			return;
		}
		if (ndef.getMaxSize() < size) {
			showToast("文件大小超出容量");
			return;
		}

		ndef.writeNdefMessage(message);
		showToast("写入数据成功.");
		return;
	} else {
		var format = NdefFormatable.get(tag);
		if (format != null) {
			try {
				format.connect();
				format.format(message);
				showToast("格式化tag并且写入message");
				return;
			} catch (e) {
				showToast("格式化tag失败.");
				return;
			}
		} else {
			showToast("Tag不支持NDEF");
			return;
		}
	}
}
/**
 * 读取内容
 */
function __read(intent) {
	var Parcelable = plus.android.importClass("android.os.Parcelable");
	var rawmsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
	if (rawmsgs) {
		const records = rawmsgs[0].getRecords();
		var result = records[0].getPayload();
		var s = plus.android.newObject("java.lang.String", result);
		if (typeof s === 'string') {
			showToast("数据内容:" + s);
		} else {
			console.log(s)
			showToast('数据为空')
		}
	} else {
		showToast('数据为空')
	}

}

/**
 * 读取卡号
 */
function __read_no(intent) {
	var content = "";
	var tag = plus.android.importClass("android.nfc.Tag");
	tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	var bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
	console.log("bytesId:" + (bytesId));
	content += "卡片字节数组ID：" + tag.getId() + "<br/>";
	content += "卡片16进制ID：" + bytesToHexString(tag.getId()) + "<br/>";
	var tagid = reverseTwo(bytesToHexString(tag.getId()));
	content += "卡片16进制翻转ID：" + tagid + "<br/>";
	content += "卡片10进制卡号：" + parseInt(tagid, 16) + "<br/>";
	uni.showToast({
		title: parseInt(tagid, 16),
		icon: 'none',
		duration: 3000
	})
	console.log(content)
}


function bytesToHexString(inarray) {
	var i, j, x;
	var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
		"B", "C", "D", "E", "F"
	];
	var out = "";
	for (j = 0; j < inarray.length; ++j) {
		x = parseInt(inarray[j]) & 0xff;
		i = (x >> 4) & 0x0f;
		out += hex[i];
		i = x & 0x0f;
		out += hex[i];
	}
	return out;
}

function reverseTwo(str) {

	var str1 = "";
	for (var i = 1; i <= str.length; i++) {
		str1 += str[i - 1];
		if (i % 2 == 0) {
			if (i == str.length) {
				break;
			}
			str1 += ":";
		}
	}
	var str2 = "";
	for (var i = str1.split(":").length - 1; i >= 0; i--) {
		str2 += str1.split(":")[i];
	}
	return str2;
}

function close() {
	if (nfc) {
		let main = plus.android.runtimeMainActivity();
		nfc.disableForegroundDispatch(main);
	}
}

//Key处理函数  
function hexStringToByteArray(key) {
	let hexA = new Array();
	let pos = 0;
	let len = key.length / 2;
	for (let i = 0; i < len; i++) {
		let s = key.substr(pos, 2);
		let v = parseInt(s, 16);
		if (v >= 128)
			v = v - 256;
		hexA.push(v);
		pos += 2;
	}
	return hexA;
}

//数组转字符串
function byteArrayToHexString(data) {
	let i, j, inn;
	let hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
	let out = '';
	for (j = 0; j < data.length; ++j) {
		inn = data[j] & 0xff;
		i = (inn >>> 4) & 0x0f;
		out += hex[i];
		i = inn & 0x0f;
		out += hex[i];
	}
	return out;
}